package cn.gan.loveofsoul.commons.utils;

import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;
import java.util.List;
import java.util.Map;
import java.util.Properties;


public class ConfigUtil {

	/**
	 * 获取配置文件中的属性
	 * 
	 * @param service_name
	 * @return
	 */
	private static final Log logger = LogFactory.getLog(ConfigUtil.class);

	public static String getProperties(String service_name) {
		InputStream inputStream = ConfigUtil.class.getClassLoader()
				.getResourceAsStream("config/config.properties");
		Properties p = new Properties();
		String param = null;
		try {
			p.load(inputStream);
		} catch (IOException e1) {
			e1.printStackTrace();
			logger.info("服务信息加载错误");
		}
		if (p.containsKey(service_name)) {
			param = p.getProperty(service_name);
		} else {
			logger.info("服务信息没有配置");
		}
		return param;
	}

	// 加密
	public static String encode(String key, String data) throws Exception {
		DESKeySpec dks = new DESKeySpec(key.getBytes("GB18030"));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		// key的长度不能够小于8位字节
		Key secretKey = keyFactory.generateSecret(dks);
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		IvParameterSpec iv = new IvParameterSpec(getProperties("xlKey").getBytes());// 向量
		AlgorithmParameterSpec paramSpec = iv;
		cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
		byte[] bytes = cipher.doFinal(data.getBytes("GB18030"));
		return new String(Base64.encode(bytes));
	}

	// 解密算法：
	public static byte[] decode(String key, String data) throws Exception {
		try {
			DESKeySpec dks = new DESKeySpec(key.getBytes("GB18030"));
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			// key 的长度不能够小于 8 位字节
			Key secretKey = keyFactory.generateSecret(dks);
			Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			IvParameterSpec iv = new IvParameterSpec(getProperties("xlKey").getBytes());
			AlgorithmParameterSpec paramSpec = iv;
			cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
			return cipher.doFinal(Base64.decode(data.getBytes()));
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		}
	}

	/***********百度接口调用 辅助工具 *************/
	public static String post(String requestUrl, String accessToken, String params) throws Exception {
		String generalUrl = requestUrl + "?access_token=" + accessToken;
		URL url = new URL(generalUrl);
		// 打开和URL之间的连接
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("POST");
		// 设置通用的请求属性
		connection.setRequestProperty("Content-Type", "application/json");
		connection.setRequestProperty("Connection", "Keep-Alive");
		connection.setUseCaches(false);
		connection.setDoOutput(true);
		connection.setDoInput(true);

		// 得到请求的输出流对象
		DataOutputStream out = new DataOutputStream(connection.getOutputStream());
		out.writeBytes(params);
		out.flush();
		out.close();

		// 建立实际的连接
		connection.connect();
		// 获取所有响应头字段
		Map<String, List<String>> headers = connection.getHeaderFields();
		// 遍历所有的响应头字段
		for (String key : headers.keySet()) {
			System.out.println(key + "--->" + headers.get(key));
		}
		// 定义 BufferedReader输入流来读取URL的响应
		BufferedReader in = null;
		if (requestUrl.contains("nlp")) {
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
		} else {
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
		}
		String result = "";
		String getLine;
		while ((getLine = in.readLine()) != null) {
			result += getLine;
		}
		in.close();
		System.out.println("result:" + result);
		return result;
	}

	public static String getAuth() {
		// 获取token地址
		String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
		// 官网获取的 API Key 更新为你注册的
		String clientId = "G2cdUijG9Utr3R6HNTOWGLb5";
		// 官网获取的 Secret Key 更新为你注册的
		String clientSecret = "yBPTcyjd4H7uFvlWXGNXP2NYojNS4RfY";
		String getAccessTokenUrl = authHost
				// 1. grant_type为固定参数
				+ "grant_type=client_credentials"
				// 2. 官网获取的 API Key
				+ "&client_id=" + clientId
				// 3. 官网获取的 Secret Key
				+ "&client_secret=" + clientSecret;
		try {
			URL realUrl = new URL(getAccessTokenUrl);
			// 打开和URL之间的连接
			HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
			connection.setRequestMethod("GET");
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String result = "";
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			/**
			 * 返回结果示例
			 */
			JSONObject jsonObject = JSONObject.parseObject(result);
			String access_token = jsonObject.getString("access_token");
			return access_token;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
}